package com.tbm.console.util;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class EntityAttributeUtil {


    /**
     * 通过CLass名，可以获取所有属性和中文说明
     * @param clazz
     * @return
     */
    public static List<PageData> entityAttributeWithZH(Class clazz){
        Field[] declaredFields = clazz.getDeclaredFields();
        List<String> name = new ArrayList<>();
        for(int i=0;i<declaredFields.length;i++){
            String filed = declaredFields[i].getName();
            name.add(filed);
        }
        List<PageData> list = entityAttributeWithZH(clazz, name);
        return list;
    }

    /**
     * 通过Class名，可以获取所有的属性
     * @param clazz
     * @return
     */
    public static List<String> entityAttribute(Class clazz){
        Field[] declaredFields = clazz.getDeclaredFields();
        List<String> attrs = new ArrayList<>();
        for(int i=0;i<declaredFields.length;i++){
            String filed = declaredFields[i].getName();
            attrs.add(filed);
        }
        return attrs;
    }

    /**
     * 通过类名获取
     * @param clazz
     * @param name
     * @return
     */
    public static List<PageData> entityAttributeWithZH(Class clazz,List<String> name){

        List<PageData> list = new ArrayList<>();
        for(int i=0;i<name.size();i++){
            String filed = name.get(i);
            PageData pageData = new PageData();
            pageData.put("field",filed);
            try {
                Method getFielzh  = clazz.getMethod("get"+filed.substring(0,1).toUpperCase()+filed.substring(1)+"ZH");
                pageData.put("fieldzh", getFielzh.invoke(clazz.newInstance()));
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            list.add(pageData);
        }
        //表示0
        if(name.size()==0){
            PageData pageData = new PageData();
            pageData.put("field","id");
            pageData.put("fieldzh","编号");
            list.add(pageData);
        }
        return list;
    }



}
